/*
 * @Author: 李金深 2896583081@qq.com
 * @Date: 2023-07-05 18:18:25
 * @LastEditors: 李金深 2896583081@qq.com
 * @LastEditTime: 2023-08-02 10:24:42
 * @FilePath: /com.huizhouyiren.web.d0101/src/components/navbar/notify.js
 * @Description: 通知
 */
import { ref } from 'vue'
import createNotify from '@/hooks/userBrowserNotify'
import { debounce } from '@/utils/tools'
import use$i18n from '@/hooks/use$i18n.js'
import mitt from '@/mitt/index'
import { useSystem } from '@/stores/system'
import { useChat } from '@/stores/chat'
import { useEmail } from '@/stores/email'

export default function () {
  const $t = use$i18n()
  const systemStore = useSystem()
  const chatStore = useChat()
  const emailStore = useEmail()
  let visibility = ref(false)
  document.addEventListener('visibilitychange', () => {
    // 用户息屏、或者切到后台运行 （离开页面）
    if (document.visibilityState === 'hidden') {
      visibility.value = false
      // console.log('隐藏了')
    }
    // 用户打开或回到页面
    if (document.visibilityState === 'visible') {
      visibility.value = true

      // console.log('页面可见')
      debounce(
        () => {
          let user_token = localStorage.getItem('USER_TOKEN')
          if (user_token) {
            emailStore.getEmailUnread()
            chatStore.getLatelyList()
          }
        },
        1000,
        true
      )
    }
  })

  const newNotify = (msg) => {
    console.log('zhjixle')
    if (!visibility.value) {
      createNotify({
        title: $t('system.systemNotice'),
        options: {
          badge: systemStore.logo,
          body: msg
        },
        duration: 5000
      })
    }
    // if (this.$route.fullPath != "/index/sales/chat") {
    //     if (!this.timer) {
    //         let info = $t('msgNotify.msgNotify')
    //         this.timer = setInterval(() => {
    //             document.title = info.substring(1, info.length) + info.substring(0, 1)
    //             info = document.title.substring(0, info.length)
    //         }, 500);
    //     }
    // }
  }
  mitt.on('messageNotify', () => {
    console.log('消息通知')
    debounce(() => {
      newNotify($t('system.msgNotify'))
    }, 1500)
  })
  mitt.on('emailNotify', () => {
    debounce(() => {
      newNotify($t('system.emailNotify'))
    }, 1500)
  })
}
